package socketmvc.core.packets.biz;

import socketmvc.core.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SockMultiFile implements Iterable<SockFile>,Serializable {

    private final List<SockFile> files;

    public SockMultiFile(byte[][] bytes) {
        int nameIndex = 0;
        files = new ArrayList<>(bytes.length);
        for (byte[] aBytes : bytes) {
            files.add(new SockFile(aBytes,"unknown-"+(++nameIndex)));
        }
    }

    public SockMultiFile(List<SockFile> files) {
        this.files = files;
    }

    public List<SockFile> getFiles(){
        return files;
    }

    public SockFile getFile(int index){
        return files.get(0);
    }

    public boolean isEmpty(){
        return files == null || files.isEmpty();
    }

    public int getNumOfFiles(){
        return files != null ? files.size() :0;
    }

    /**
     * 获取文件总体积
     * @param sizeUnit 体积单位 取值B(byte),K(kb),M(mb),G(gb),默认值是B
     * @return 体积
     */
    public int getTotalSizeOfFiles(String sizeUnit){
        int totalLen = 0;
        for (SockFile file : this) {
            totalLen = totalLen+file.getSize();
        }
        if (StringUtils.isEmpty(sizeUnit)){
            return totalLen;
        }
        return switch (sizeUnit) {
            case "K" -> totalLen / 1024;
            case "M" -> totalLen / 1024 / 1024;
            case "G" -> totalLen / 1024 / 1024 / 1024;
            default -> totalLen;
        };
    }

    public void part(){
        int totalLen = 0;
        for (SockFile file : this) {
            file.setStartIndex(totalLen);
            totalLen = totalLen + file.getSize();
            file.setEndIndex(totalLen - 1);
        }
        for (SockFile file : this) {
            file.setTotalLength(totalLen);
        }
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     * @return an Iterator.
     */
    @Override
    public Iterator<SockFile> iterator() {
        return files.iterator();
    }
}
